<template>
  <div class="dashboard-container">
    <h2 class="page-title">医生工作台</h2>

    <el-row :gutter="20" class="overview-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <div class="overview-item">
            <el-icon class="overview-icon patient-icon"><UserFilled /></el-icon>
            <div class="overview-content">
              <div class="overview-title">总患者数</div>
              <div class="overview-value">{{ totalPatients }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <div class="overview-item">
            <el-icon class="overview-icon consultation-icon"><Calendar /></el-icon>
            <div class="overview-content">
              <div class="overview-title">今日看诊</div>
              <div class="overview-value">{{ todayConsultations }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <div class="overview-item">
            <el-icon class="overview-icon transaction-icon"><Money /></el-icon>
            <div class="overview-content">
              <div class="overview-title">本月交易</div>
              <div class="overview-value">¥{{ monthlyTransactions.toLocaleString() }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <div class="overview-item">
            <el-icon class="overview-icon doctor-icon"><Mug /></el-icon>
            <div class="overview-content">
              <div class="overview-title">活跃医生</div>
              <div class="overview-value">{{ activeDoctors }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-section">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>看诊趋势</span>
              <el-select v-model="selectedTimeRange" placeholder="选择时间范围" size="small" style="width: 120px;" @change="updateBarChartData">
                <el-option label="最近7天" value="7days"></el-option>
                <el-option label="最近30天" value="30days"></el-option>
                <el-option label="最近1年" value="1year"></el-option>
              </el-select>
            </div>
          </template>
          <div ref="barChart" class="chart-instance"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>患者构成</span>
              <el-select v-model="selectedCategory" placeholder="选择分类" size="small" style="width: 120px;" @change="updatePieChartData">
                <el-option label="年龄分布" value="age"></el-option>
                <el-option label="性别比例" value="gender"></el-option>
              </el-select>
            </div>
          </template>
          <div ref="pieChart" class="chart-instance"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { UserFilled, Calendar, Money, Mug } from '@element-plus/icons-vue' // 导入Element Plus图标

// --- 概览数据 ---
const totalPatients = ref(1500)
const todayConsultations = ref(45)
const monthlyTransactions = ref(320000)
const activeDoctors = ref(28)

// --- 图表数据和实例 ---
const barChart = ref(null)
const pieChart = ref(null)
let myBarChart = null // 存储ECharts实例
let myPieChart = null // 存储ECharts实例

// 筛选条件
const selectedTimeRange = ref('7days');
const selectedCategory = ref('age');

// --- ECharts 配置和初始化 ---

const getBarChartOptions = (timeRange) => {
  let xAxisData = [];
  let seriesData = [];

  // 模拟数据生成
  if (timeRange === '7days') {
    xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    seriesData = [23, 34, 45, 56, 34, 22, 31];
  } else if (timeRange === '30days') {
    xAxisData = Array.from({length: 30}, (_, i) => `${i + 1}日`);
    seriesData = Array.from({length: 30}, () => Math.floor(Math.random() * 80) + 10);
  } else if (timeRange === '1year') {
    xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
    seriesData = Array.from({length: 12}, () => Math.floor(Math.random() * 200) + 50);
  }

  return {
    title: {
      text: `${timeRange === '7days' ? '最近7天' : timeRange === '30days' ? '最近30天' : '最近1年'}看诊趋势`,
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLabel: {
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '看诊人数',
      nameTextStyle: {
        color: '#666'
      },
      axisLabel: {
        color: '#666'
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#f0f0f0'
        }
      }
    },
    series: [{
      name: '看诊人数',
      data: seriesData,
      type: 'bar',
      smooth: true, // 可以尝试平滑曲线
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.1)'
      },
      itemStyle: {
        borderRadius: [5, 5, 0, 0], // 柱状图圆角
        color: new echarts.graphic.LinearGradient( // 渐变色
            0, 0, 0, 1,
            [
              { offset: 0, color: '#409EFF' }, // 0% 处的颜色
              { offset: 1, color: '#a0cfff' }  // 100% 处的颜色
            ]
        )
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient( // 悬浮渐变色
              0, 0, 0, 1,
              [
                { offset: 0, color: '#2b85e4' },
                { offset: 1, color: '#66b1ff' }
              ]
          )
        }
      }
    }]
  };
};

const getPieChartOptions = (category) => {
  let pieData = [];
  let chartTitle = '';

  if (category === 'age') {
    chartTitle = '患者年龄分布';
    pieData = [
      { value: 320, name: '0-18岁' },
      { value: 240, name: '19-35岁' },
      { value: 560, name: '36-60岁' },
      { value: 380, name: '60岁以上' },
    ];
  } else if (category === 'gender') {
    chartTitle = '患者性别比例';
    pieData = [
      { value: 700, name: '男性' },
      { value: 800, name: '女性' },
    ];
  }

  return {
    title: {
      text: chartTitle,
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)' // 格式化提示框内容
    },
    legend: {
      orient: 'vertical', // 垂直布局
      left: 'left', // 靠左显示
      bottom: 'center', // 垂直居中
      data: pieData.map(item => item.name),
      textStyle: {
        color: '#666'
      }
    },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'], // 内外半径，形成环形图
      center: ['65%', '50%'], // 图表中心位置
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false, // 默认不显示标签
        position: 'center'
      },
      emphasis: { // 鼠标悬浮时的样式
        label: {
          show: true,
          fontSize: 20,
          fontWeight: 'bold',
          formatter: '{b}\n{d}%' // 悬浮时显示名称和百分比
        }
      },
      labelLine: {
        show: false
      },
      data: pieData,
      // 颜色板
      color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#7950F2']
    }]
  };
};


const initCharts = () => {
  if (barChart.value) {
    myBarChart = echarts.init(barChart.value);
    myBarChart.setOption(getBarChartOptions(selectedTimeRange.value));
  }
  if (pieChart.value) {
    myPieChart = echarts.init(pieChart.value);
    myPieChart.setOption(getPieChartOptions(selectedCategory.value));
  }
}

const updateBarChartData = () => {
  if (myBarChart) {
    myBarChart.setOption(getBarChartOptions(selectedTimeRange.value), true); // true表示不合并旧配置
  }
}

const updatePieChartData = () => {
  if (myPieChart) {
    myPieChart.setOption(getPieChartOptions(selectedCategory.value), true);
  }
}

// --- 生命周期钩子 ---
onMounted(() => {
  initCharts();
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    myBarChart?.resize();
    myPieChart?.resize();
  });
});

onUnmounted(() => {
  // 组件卸载时销毁图表实例，防止内存泄漏
  myBarChart?.dispose();
  myPieChart?.dispose();
  window.removeEventListener('resize', () => {
    myBarChart?.resize();
    myPieChart?.resize();
  });
});
</script>

<style scoped>
.dashboard-container {
  padding: 30px; /* 页面内边距 */
  background-color: #f8fbfd; /* 页面背景色 */
  min-height: calc(100vh - 60px); /* 适应主布局高度 */
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 30px;
  text-align: center;
  position: relative;
}

.page-title::after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: -10px;
  transform: translateX(-50%);
  width: 60px;
  height: 4px;
  background-color: #409EFF;
  border-radius: 2px;
}

/* 概览卡片区域 */
.overview-cards {
  margin-bottom: 30px;
}

.overview-card {
  border-radius: 12px; /* 圆角卡片 */
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); /* 柔和阴影 */
  transition: all 0.3s ease; /* 悬停动画 */
  background-color: #fff; /* 确保白色背景 */
}

.overview-card:hover {
  transform: translateY(-5px); /* 悬停上移效果 */
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12); /* 悬停阴影加深 */
}

.overview-item {
  display: flex;
  align-items: center;
  justify-content: center; /* 居中内容 */
  padding: 10px 0;
}

.overview-icon {
  font-size: 48px; /* 图标大小 */
  margin-right: 15px;
  width: 60px; /* 确保图标容器大小一致 */
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%; /* 圆形图标背景 */
  color: #fff; /* 图标颜色 */
  box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}

/* 根据不同图标设置背景色 */
.patient-icon { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); } /* 紫色渐变 */
.consultation-icon { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); } /* 蓝色渐变 */
.transaction-icon { background: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%); } /* 粉蓝渐变 */
.doctor-icon { background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%); } /* 绿蓝渐变 */


.overview-content {
  text-align: left; /* 内容左对齐 */
}

.overview-title {
  font-size: 16px;
  color: #666;
  margin-bottom: 5px; /* 减小标题与值的间距 */
  font-weight: 500;
}

.overview-value {
  font-size: 32px; /* 增大数值字号 */
  font-weight: bold;
  color: #333;
  letter-spacing: 1px; /* 字母间距 */
}

/* 图表区域 */
.chart-section {
  margin-top: 30px;
}

.chart-card {
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  background-color: #fff;
}

.chart-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5; /* 标题下划线 */
}

.chart-instance {
  width: 100%;
  height: 300px; /* 保持图表高度一致 */
}
</style>